﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;

namespace AzureTracer.Common
{
    public static class VisualTree
    {
        public static FrameworkElement GetVisualParent(
            this FrameworkElement childElement)
        {
            return VisualTreeHelper.GetParent(childElement) as FrameworkElement;
        }

        public static IEnumerable<TAncestor> GetVisualAncestors<TAncestor>
            (this FrameworkElement descendentElement) where TAncestor : DependencyObject
        {         
            FrameworkElement parent = descendentElement.GetVisualParent();
            while (parent != null)
            {
                TAncestor item = parent as TAncestor;
                if (item != null)                
                    yield return item;
                
                parent = parent.GetVisualParent();
            }
        }

        public static IEnumerable<TDescendent> GetVisualDescendents<TDescendent>
            (this DependencyObject root) where TDescendent : DependencyObject
        {
            int count = VisualTreeHelper.GetChildrenCount(root);
            for (int i = 0; i < count; i++)
            {
                var child = VisualTreeHelper.GetChild(root, i);
                TDescendent item = child as TDescendent;
                if (item != null)
                    yield return item;

                foreach (var descendent in child.GetVisualDescendents<TDescendent>())
                    yield return descendent;
            }
        }

    }
}
